<template>
  <van-popup
    class="datePicker"
    v-model:show="isSHowPicker"
    round
    close-on-popstate
    safe-area-inset-bottom
    position="bottom"
    @click-overlay="popupClose"
  >
    <div class="popup">
      <!-- tab工具栏 -->
      <div class="popup-header items-center">
        <div class="items-center">
          <div
            :class="{ 'popup-header-activity': popup.type === 1 }"
            style="margin-right: 20px"
            @click="popupTypeChange(1)"
          >
            {{ t("mvp.incomeStatement.ayuecx") }}
            <!-- tab 标记 -->
            <div v-if="popup.type === 1" class="popup-header-line"></div>
          </div>
          <div
            :class="{ 'popup-header-activity': popup.type > 1 }"
            @click="popupTypeChange(2)"
          >
            {{ t("mvp.incomeStatement.antcx") }}
            <!-- tab 标记 -->
            <div v-if="popup.type > 1" class="popup-header-line"></div>
          </div>
        </div>
        <div style="width: 20px; height: 20px">
          <Images src="/image/assetDetails/close.svg" @click="popupClose" />
        </div>
      </div>
      <!-- 按月 -->
      <van-date-picker
        v-if="popup.type === 1"
        v-model="popup.monthsObj.currentDate"
        :show-toolbar="false"
        title=""
        :min-date="popup.monthsObj.minDate"
        :max-date="popup.monthsObj.maxDate"
        :columns-type="popup.monthsObj.columnsType"
        visible-option-num="3"
        swipe-duration="100"
      />
      <!-- 按天 -->
      <div v-else class="popup-custom">
        <!-- 交易时间 -->
        <div class="popup-custom-moth">
          <div class="popup-custom-label">
            {{ t("mvp.incomeStatement.jysj") }}
          </div>
          <div class="items-center popup-custom-moth-content">
            <div
              class="popup-custom-moth-btn"
              :class="{ 'popup-custom-moth-activity': popup.type === 3 }"
              @click="popupTypeChange(3)"
            >
              {{ t("mvp.incomeStatement.sy") }}
            </div>
            <div
              class="popup-custom-moth-btn"
              :class="{ 'popup-custom-moth-activity': popup.type === 4 }"
              @click="popupTypeChange(4)"
            >
              {{ t("mvp.zj90t") }}
            </div>
          </div>
        </div>
        <!-- 自定义 -->
        <div class="popup-custom-date">
          <div class="popup-custom-label">
            {{ t("mvp.incomeStatement.custom") }}
          </div>
          <!-- 开始、结束-日期显示 -->
          <div class="items-center popup-custom-moth-content">
            <div
              class="popup-custom-date-btn"
              :class="{ 'popup-custom-date-activity': popup.type === 5 }"
              @click.stop="popupTypeChange(5)"
            >
              {{ popup.start.currentDate.join(".") }}
            </div>
            <div class="popup-custom-date-line"></div>
            <div
              class="popup-custom-date-btn"
              :class="{ 'popup-custom-date-activity': popup.type === 6 }"
              @click.stop="popupTypeChange(6)"
            >
              {{ popup.end.currentDate.join(".") }}
            </div>
          </div>
          <!-- 日期选择 -->
          <van-date-picker
            v-if="popup.type === 5"
            v-model="popup.start.currentDate"
            :show-toolbar="false"
            title=""
            :min-date="popup.start.minDate"
            :max-date="popup.start.maxDate"
            :columns-type="popup.start.columnsType"
            visible-option-num="3"
            swipe-duration="100"
            @change="startDateChange"
          />
          <van-date-picker
            v-if="popup.type === 6"
            v-model="popup.end.currentDate"
            :show-toolbar="false"
            title=""
            :min-date="popup.end.minDate"
            :max-date="popup.end.maxDate"
            :columns-type="popup.end.columnsType"
            swipe-duration="100"
            visible-option-num="3"
          />
        </div>
        <!-- 最大提示 -->
        <div class="popup-custom-desc">
          *{{ t("mvp.incomeStatement.maxDesc") }}
        </div>
      </div>
      <!-- 确认按钮 -->
      <div class="popup-bottom">
        <div class="popup-bottom-btn" @click.stop="confirm">
          {{ t("common.confirm") }}
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script setup name="datePicker" lang="ts">
import { useDateFormat } from "@vueuse/core";

const { t } = useI18n();
// 属性
const props = withDefaults(
  defineProps<{
    show: boolean;
    startTimestamp?: string | number; // 最小时间
    endTimestamp?: string | number; // 最大时间
  }>(),
  {
    show: false,
  }
);
const isSHowPicker = ref(false);
watch(
  () => props.show,
  (newVal) => {
    isSHowPicker.value = !!newVal;
  }
);
const emit = defineEmits(["update:show", "confirm"]);

// 弹窗属性
const popup = reactive({
  type: 1, // -1：没有选择  1： 按月  2：按天 3：上个月 4：近3 个月 5：开始时间  6：结束时间
  monthsObj: {
    currentDate: ["2021", "01"],
    columnsType: ["year", "month"],
    minDate: props.startTimestamp
      ? new Date(props.startTimestamp)
      : new Date("2023/01/01"),
    maxDate: new Date(),
  },
  // 交易时间
  tradingTime: "1", // 1：上个月 2：近三月
  // 开始、结束
  start: {
    currentDate: ["2021", "01"],
    columnsType: ["year", "month", "day"],
    minDate: props.startTimestamp
      ? new Date(props.startTimestamp)
      : new Date("2023/01/01"),
    maxDate: new Date(),
  },
  end: {
    currentDate: ["2021", "01"],
    columnsType: ["year", "month", "day"],
    minDate: props.startTimestamp
      ? new Date(props.startTimestamp)
      : new Date("2023/01/01"),
    maxDate: new Date(),
  },
});

onMounted(() => {
  // 初始化日期选择期的数据
  initDate();
});

onBeforeUnmount(() => {
  endTimestamp_watch && endTimestamp_watch();
});

const initDate = () => {
  let curt: any = null;
  if (props.endTimestamp) {
    curt = new Date(Number(props.endTimestamp));
  } else {
    curt = new Date();
  }

  // 按月
  popup.monthsObj.currentDate = [
    curt.getFullYear() + "",
    curt.getMonth() + 1 + "",
  ];
  // popup.monthsObj.minDate = new Date(curt.getFullYear() - 3, 0);
  popup.monthsObj.minDate = props.startTimestamp
    ? new Date(props.startTimestamp)
    : new Date("2023/01/01");
  popup.monthsObj.maxDate = new Date(curt.getFullYear(), curt.getMonth());
  // 按天
  popup.start.currentDate = [
    curt.getFullYear() + "",
    curt.getMonth() + 1 + "",
    "1",
  ];
  popup.start.minDate = props.startTimestamp
    ? new Date(props.startTimestamp)
    : new Date("2023/01/01");

  // 如果有截止时间的时间戳,那么开始时间不能等于结束时间: 避免出现 2024/07/14 ~ 2024/07/14的场景
  // if (props.endTimestamp) {
  //   popup.start.maxDate = new Date(
  //     Number(props.endTimestamp) - 24 * 60 * 60 * 1000
  //   );
  // } else {
  // popup.start.maxDate = curt;
  // }
  popup.start.maxDate = curt;
  popup.end.currentDate = [
    curt.getFullYear() + "",
    curt.getMonth() + 1 + "",
    curt.getDate() + "",
  ];
  popup.end.minDate = new Date(curt.getFullYear(), curt.getMonth(), 1);
  popup.end.maxDate = curt;
};

// 如果,结束时间变化了,更新一下数据源
const endTimestamp_watch = watch(
  () => props.endTimestamp,
  (newVal) => {
    if (newVal) {
      initDate();
    }
  }
);

//  确认按钮
const confirm = () => {
  // 1. 获取当前选择的时间戳
  let start = 0;
  let end = 0;
  const curt = new Date();
  // 获取上一个月的天数
  function getDaysInMonth(year: string | number, month: string | number) {
    // 注意：month 是从 0 开始的（0 代表一月），所以计算时需要 +1
    // Date 的日期参数 day 设置为 0 会回到上个月的最后一天
    return new Date(Number(year), Number(month) - 1, 0).getDate();
  }
  if (popup.type === 1) {
    const t = popup.monthsObj.currentDate.join("/");
    start = new Date(`${t}/01`).getTime();
    // console.log(start, "按月选择：", t);
    const d = getDaysInMonth(
      popup.monthsObj.currentDate[0],
      Number(popup.monthsObj.currentDate[1]) + 1
    );
    // console.log(popup.monthsObj.currentDate[1], "上个月有：", d, "天");
    end = new Date(`${t}/${d} 23:59:59`).getTime();
    // console.log("结束时间:", end);
  } else if (popup.type === 2) {
    start = 0;
  } else if (popup.type === 3) {
    const d = getDaysInMonth(curt.getFullYear(), Number(curt.getMonth()) + 1);
    // console.log(d, "----", curt.getMonth());
    if (curt.getMonth() > 0) {
      start = new Date(curt.getFullYear(), curt.getMonth() - 1, 1).getTime();
    } else {
      start = new Date(curt.getFullYear() - 1, 11, 1).getTime();
    }
    end = new Date(
      curt.getFullYear(),
      curt.getMonth() - 1,
      d,
      23,
      59,
      59
    ).getTime();
  } else if (popup.type === 4) {
    const begin = new Date(curt.getTime() - 3 * 30 * 24 * 60 * 60 * 1000);
    start = new Date(
      `${begin.getFullYear()}/${begin.getMonth() + 1}/${
        begin.getDate() + 1
      } 00:00:00`
    ).getTime();
    end = curt.getTime();
  } else if (popup.type === 5 || popup.type === 6) {
    start = new Date(popup.start.currentDate.join("/")).getTime();
    end =
      new Date(popup.end.currentDate.join("/")).getTime() +
      23 * 60 * 60 * 1000 +
      59 * 60 * 1000 +
      59 * 1000;
  } else {
    start = 0;
  }
  // 重置 自定义时间
  if (popup.type != 5 && popup.type != 6 && !props.endTimestamp) {
    popup.start.currentDate = [
      curt.getFullYear() + "",
      curt.getMonth() + 1 + "",
      "1",
    ];
    popup.end.currentDate = [
      curt.getFullYear() + "",
      curt.getMonth() + 1 + "",
      curt.getDate() + "",
    ];
  }
  console.log(
    start,
    "请求-开始-时间：",
    useDateFormat(start, "YYYY-MM-DD HH:mm:ss").value
  );
  console.log(
    end,
    "请求-结束-时间：",
    useDateFormat(end, "YYYY-MM-DD HH:mm:ss").value
  );
  // 2. 将时间传递出去
  emit("confirm", { start, end, type: popup.type });
  // 3. 关闭弹窗
  popupClose();
};
// 弹窗切换
const popupTypeChange = (val: number) => {
  // console.log("type--", val);
  if (val > 0) {
    popup.type = val;
    if (val === 3 || val === 4) confirm();
  } else {
    popup.type = -1;
  }
};
// 关闭弹窗
const popupClose = () => {
  emit("update:show", false);
};
// 选择自定义时间
const startDateChange = ({ selectedValues }: any) => {
  const end_time = new Date(popup.end.currentDate.join("/")).getTime();
  const start_time = new Date(selectedValues.join("/")).getTime();
  const max90 = 89 * 24 * 60 * 60 * 1000; // 这里减去一天,是因为结束时间是 23:59:59
  const cut = new Date();
  const now = cut.getTime();
  // console.log("--end_time:", end_time);
  // console.log(end_time <= start_time, "--start_time:", start_time);

  // 1. 结束时间 > 开始时间 && 结束时间 - 开始时间 > 90 天
  if (end_time - start_time > max90) {
    const e = new Date(start_time + max90);
    popup.end.currentDate = [
      e.getFullYear() + "",
      e.getMonth() + 1 + "",
      e.getDate() + "",
    ];
    popup.end.maxDate = e;
  }
  // 开始时间 >= 结束时间
  else if (end_time <= start_time) {
    let sjc = start_time + max90;
    if (sjc > Number(props.endTimestamp)) {
      sjc = Number(props.endTimestamp);
    }

    const e = new Date(sjc);
    if (e.getTime() <= now) {
      popup.end.currentDate = [
        e.getFullYear() + "",
        e.getMonth() + 1 + "",
        e.getDate() + "",
      ];
      popup.end.maxDate = e;
    } else {
      popup.end.currentDate = [
        cut.getFullYear() + "",
        cut.getMonth() + 1 + "",
        cut.getDate() + "",
      ];
      popup.end.maxDate = cut;
    }
  }
  // 正常
  else {
    let sjc = start_time + max90;
    if (sjc <= now) {
      if (sjc > Number(props.endTimestamp)) {
        sjc = Number(props.endTimestamp);
      }
      popup.end.maxDate = new Date(sjc);
    } else {
      if (now > Number(props.endTimestamp)) {
        sjc = Number(props.endTimestamp);
        popup.end.maxDate = new Date(sjc);
      } else {
        popup.end.maxDate = cut;
      }
    }
  }
  // 结束时间的最小值，始终要等于开始时间
  popup.end.minDate = new Date(start_time);
};
</script>
<style scoped lang="scss">
.datePicker {
}
.popup {
  padding-bottom: 10 * 2px;
  &-header {
    height: 50 * 2px;
    padding: 0 15 * 2px;
    width: 100vw;
    justify-content: space-between;
    font-size: 15 * 2px;
    font-weight: 590;
    color: #999da7;
    border-bottom: 1 * 2px solid rgba(0, 0, 0, 0.1);

    &-activity {
      position: relative;
      color: #007bff !important;
    }

    &-line {
      position: absolute;
      left: 50%;
      bottom: -15 * 2px;
      transform: translate(-50%, 0);
      width: 16 * 2px;
      height: 3 * 2px;
      border-radius: 3 * 2px;
      background-color: #007bff;
    }
  }

  &-bottom {
    margin: 20 * 2px 15 * 2px;
    margin-bottom: var(--safe-area-inset-bottom);
    background-color: #007bff;
    height: 48 * 2px;
    border-radius: 6 * 2px;

    &-btn {
      line-height: 48 * 2px;
      text-align: center;
      color: #fff;
      font-size: 15 * 2px;
      font-weight: 590;
    }
  }

  &-custom {
    &-label {
      margin-left: 8 * 2px;
      font-size: 14 * 2px;
      font-weight: 510;
      color: #141924;
    }

    &-label::after {
      position: absolute;
      left: 0;
      top: 6 * 2px;
      content: "";
      width: 3 * 2px;
      height: 6 * 2px;
      background-color: #007bff;
      border-radius: 100px;
    }

    &-moth {
      position: relative;
      margin: 20 * 2px 15 * 2px;

      &-content {
        margin-top: 10 * 2px;
        justify-content: space-between;
      }

      &-btn {
        padding: 6 * 2px 0;
        width: calc(50% - 38px);
        border-radius: 100px;
        font-size: 14 * 2px;
        font-weight: 510;
        color: #999da7;
        text-align: center;
        border: 1 * 2px solid #e8eaf0;
      }

      &-activity {
        color: #007bff;
        border-color: #c8e2ff;
      }
    }

    &-date {
      position: relative;
      margin: 20 * 2px 15 * 2px;

      &-btn {
        padding: 6 * 2px 0;
        width: calc(50% - 38px);
        border-radius: 100px;
        font-size: 14 * 2px;
        font-weight: 510;
        color: #999da7;
        text-align: center;
        border: 1 * 2px solid #e8eaf0;
      }

      &-activity {
        color: #007bff;
        border: none;
        background-color: #ecf5ff;
      }

      &-line {
        height: 1 * 2px;
        width: 30 * 2px;
        background-color: #f4f5f7;
      }
    }

    &-desc {
      font-size: 13 * 2px;
      color: #999da7;
      text-align: center;
    }
  }
}
</style>
